package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.atguigu.tingshu.common.constant.SystemConstant.ORDER_STATUS_CANCEL;
import static com.atguigu.tingshu.common.constant.SystemConstant.ORDER_STATUS_PAID;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;

    /**
     * 保存本地交易记录
     *
     * @param paymentType:支付类型 1301-订单 1302-充值
     * @param orderNo:         订单编号
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo) {
        //1. 根据订单编号查询本地交易记录 ，如果存在返回即可
        PaymentInfo paymentInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo)
        );
        if (paymentInfo != null) {
            return paymentInfo;
        }
        //2. 本地交易记录不存在，封装保存本地交易记录
        //2.1 创建本地交易记录对象
        paymentInfo = new PaymentInfo();
        //2.2 处理支付类型订单：封装交易金额跟内容
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            //2.2.1 远程调用订单服务获取订单信息，封装交易金额跟内容
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo, "订单:{}不存在", orderNo);
            //2.2.2 判断订单状态：如果订单状态为已支付或已取消，则终止业务 订单状态：0901-未支付 0902-已支付 0903-已取消
            String orderStatus = orderInfo.getOrderStatus();
            if (ORDER_STATUS_PAID.equals(orderStatus) || ORDER_STATUS_CANCEL.equals(orderStatus)) {
                throw new GuiguException(500, "订单状态有误：已支付或已取消");
            }
            //2.2.3 封装交易金额跟内容
            paymentInfo.setUserId(orderInfo.getUserId());
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            paymentInfo.setContent(orderInfo.getOrderTitle());
        }
        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            //2.3 处理支付类型充值：封装交易金额跟内容
            //2.3.1 远程调用账户服务获取充值信息，封装交易金额跟内容
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo, "充值:{}不存在", orderNo);
            //2.3.2 判断订单状态：如果订单状态为已支付或已取消，则终止业务 充值状态：0901-未支付 0902-已支付 0903-已取消
            String rechargeStatus = rechargeInfo.getRechargeStatus();
            if (ORDER_STATUS_PAID.equals(rechargeStatus) || ORDER_STATUS_CANCEL.equals(rechargeStatus)) {
                throw new GuiguException(500, "充值状态有误：已支付或已取消");
            }
            //2.3.3 封装交易金额跟内容
            paymentInfo.setUserId(rechargeInfo.getUserId());
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfo.setContent("充值：" + rechargeInfo.getRechargeAmount());
        }
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        //支付状态：1401-未支付 1402-已支付
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        //TODO 本地交易记录中：微信端交易编号、回调时间及内容 支付成功后商户收到回调通知才更新
        //paymentInfo.setOutTradeNo();
        //paymentInfo.setCallbackTime();
        //paymentInfo.setCallbackContent();
        //2.4 保存本地交易记录
        baseMapper.insert(paymentInfo);
        return paymentInfo;
    }

    /**
     * 用户付款成功后，更新本地交易记录状态
     *
     * @param transaction 微信支付交易对象
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void updatePaymentInfo(Transaction transaction) {
        //1.根据订单编号查询本地交易记录 判断状态
        String orderNo = transaction.getOutTradeNo();
        PaymentInfo paymentInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<PaymentInfo>()
                        .eq(PaymentInfo::getOrderNo, orderNo)
        );
        String paymentStatus = paymentInfo.getPaymentStatus();

        if (SystemConstant.PAYMENT_STATUS_UNPAID.equals(paymentStatus)) {
            //2.更新本地交易记录状态：状态修改为已支付、关联微信交易订单编号、回调时间、回调内容
            paymentInfo.setOutTradeNo(transaction.getTransactionId());
            paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
            paymentInfo.setCallbackTime(new Date());
            paymentInfo.setCallbackContent(transaction.toString());
            //TODO 可选 乐观锁更新： UPDATE payment_info set payment_status = '1402',callback_time = ? ,callback_content = ?,out_trade_no = ? where payment_status='1401' and order_no = ?
            baseMapper.updateById(paymentInfo);
            //支付类型：1301-订单 1302-充值
            String paymentType = paymentInfo.getPaymentType();
            //3.处理支付类型为：订单  远程调用订单服务更新订单状态
            if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
                //3.1 远程调用订单服务，更新订单支付状态以及完成虚拟物品发货
                Result result = orderFeignClient.orderPaySuccess(orderNo);

                //3.2 判断远程调用结果响应业务状态码
                if (!result.getCode().equals(200)) {
                    throw new GuiguException(500, "订单更新异常:" + orderNo);
                }
            }
            //4. 处理支付类型为：充值  远程调用账户服务更新充值状态以及完成充值业务
            if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
                Result result = accountFeignClient.rechargePaySuccess(orderNo);
                //3.2 判断远程调用结果响应业务状态码
                if (!result.getCode().equals(200)) {
                    throw new GuiguException(500, "更新充值异常:" + orderNo);
                }
            }
        }
    }
}
